package com.heima.search.service.impl;

import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.search.dto.HistorySearchDto;
import com.heima.search.pojos.ApUserSearch;
import com.heima.search.service.ApUserSearchService;
import com.heima.utils.common.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 保存用户搜索历史记录
     *
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.根据用户id和关键字查询用户是否搜索过该关键字
        ApUserSearch userSearch = mongoTemplate.findOne(Query.query(Criteria.where("keyword").is(keyword).and("userId").is(userId)), ApUserSearch.class);

        //2. 如果之前已经搜索过则更新时间
        if(null != userSearch){
            userSearch.setCreatedTime(new Date());
            mongoTemplate.save(userSearch); //既有新增也有更新的作用
            return;
        }

        //3. 查询用户所有的关键字并时间创建时间倒序排序
        Query query = Query.query(Criteria.where("userId").is(userId))
                .with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);

        //4. 判断用户的关键字是否达到10个 如果没有 则新增 如果达到了则替换最早的关键字
        userSearch = new ApUserSearch();
        userSearch.setUserId(userId);
        userSearch.setKeyword(keyword);
        userSearch.setCreatedTime(new Date());

        if(null == list || (null != list && list.size() < 10)){
            //新增
            mongoTemplate.save(userSearch);
        }else {
            //替换最高的数据
            ApUserSearch last = list.get(list.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(last.getId())), userSearch);
        }
    }

    /**
     * 查询当前登录用户的所有的搜索关键字 使用时间降序排序
     *
     * @return
     */
    @Override
    public ResponseResult findUserSearch() {
        ApUser user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.okResult(new ArrayList<ApUserSearch>());
        }
        Query query = Query.query(Criteria.where("userId").is(user.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> list = mongoTemplate.find(query, ApUserSearch.class);

        return ResponseResult.okResult(list);
    }

    /**
     * 根据id删除当前登录用户的关键字
     *
     * @param historySearchDto
     * @return
     */
    @Override
    public ResponseResult delUserSearch(HistorySearchDto historySearchDto) {
        if(null == historySearchDto || null == historySearchDto.getId()){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        ApUser user = AppThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        mongoTemplate.remove(Query
                .query(Criteria.where("id").is(historySearchDto.getId()).and("userId").is(user.getId())),ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
